package com.yxh.bigdata.zookeeper.zk;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class SimpleZkClient {

	private static final String connectString = "localhost:2181";
	private static final int sessionTimeout = 2000;
	private ZooKeeper zkClient = null;

	@Before
	public void init() throws IOException {
		zkClient = new ZooKeeper(connectString, sessionTimeout, event -> {
            //收到事件通知后的通知函数
            System.out.println(event.getType() + "====" + event.getPath());
        });
	}
	
	/**
	 * 创建节点
	 */
	@Test
	public void testCreate() throws Exception {
		//参数1：节点的路径，参数2：节点的值，参数3：节点权限，参数4：节点类型
		String nodeCreated = zkClient.create("/eclipse", "hello zk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
	}
	
	/**
	 * 判断节点是否存在
	 * @throws Exception
	 */
	@Test
	public void testExists() throws Exception {
		Stat exists = zkClient.exists("/eclipse", false);
		System.out.println(exists == null ? "not exists" : "exists" );
	}
	
	/**
	 * 获取子节点
	 */
	@Test
	public void testGetChild() throws Exception {
		List<String> children = zkClient.getChildren("/", true);
		for (String child : children) {
			System.out.println(child);
		}
	}
	
	/**
	 * 获取节点数据
	 * @throws Exception 
	 */
	@Test
	public void testGetDate() throws Exception {
		String nodeData = new String(zkClient.getData("/eclipse", false, null), "UTF-8");
		System.out.println(nodeData);
	}
	
	/**
	 * 删除节点
	 * @throws Exception
	 */
	@Test
	public void testDeleteNode() throws Exception {
		//参数2是指定删除的版本，-1代表删除所有版本
		zkClient.delete("/eclipse", -1);
	}
	
	/**
	 * 修改节点的值
	 * @throws Exception
	 */
	@Test
	public void testSetData() throws Exception {
		zkClient.setData("/eclipse", "eclipse".getBytes(), -1);
	}
}
